package com.hotacorp.opencloud.userservice.redisinfo;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;

/**
 * 获取redis运行状态类
 * @author lwg
 *
 */
@Component
public class RedisInfo {
	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	
	public Map<String, Object> info() {
		Map<String, Object> retMap = new HashMap<String, Object>();
		Properties dddddProperties = stringRedisTemplate.execute(new RedisCallback<Properties>() {
			@Override
			public Properties doInRedis(RedisConnection connection) throws DataAccessException {
				return connection.info("all");
			}
		});
		List<JSONObject> all = p2List(dddddProperties);
		retMap.put("all", all);
		Long keysNum = getKeysNum(dddddProperties);
		retMap.put("keysNum", keysNum);
		String  eeeString = (String)dddddProperties.get("used_memory");
		double iiii = 0;
		if (eeeString != null) {
			iiii = Long.parseLong(eeeString)/(1024*1024.0);
		}
		DecimalFormat format = new DecimalFormat("0.00");
		retMap.put("usedMemory", format.format(iiii));
		eeeString = (String)dddddProperties.get("used_memory_peak");
		iiii = 0;
		if (eeeString != null) {
			iiii = Long.parseLong(eeeString)/(1024*1024.0);
		}
		retMap.put("usedMemoryPeak", format.format(iiii));
		return retMap;
	}

	private List<JSONObject> p2List(Properties dddddProperties) {
		List<JSONObject> uwuJsonObjects = new ArrayList<JSONObject>();
		Enumeration<Object> keys = dddddProperties.keys();
		while (keys.hasMoreElements()) {
		      String name = (String) keys.nextElement();
		      String value = dddddProperties.getProperty(name);
		      JSONObject object = new JSONObject();
		      object.put("name", name);
		      object.put("value", value);
		      uwuJsonObjects.add(object);
		    }
		return uwuJsonObjects;
	}
	
	private Long getKeysNum(Properties dddddProperties) {
		long ret = 0;
		for (int i=0; i<16; i++) {
			String ooooString = (String)dddddProperties.get("db" + i);
			if (ooooString != null) {
				ret += getKeyNum(ooooString);
			}
		}
		return ret;
	}
	
	private long getKeyNum(String str) {
		String[] rrr = StringUtils.split(str, ",");
		long ret = 0;
		for (String iii:rrr) {
			if (iii.startsWith("keys=")) {
				String ggg = iii.substring(5);
				try {
					ret = Long.parseLong(ggg);
					break;
				} catch (Exception e) {}
			}
		}
		return ret;
	}
}
